﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.yjh;
using SmartProduction.Domain.采购委外订单;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.SupplierCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.SupplierCommandHandler
{
    public class SupplierUpdateCommandHandler : IRequestHandler<SupplierUpdateCommand, APIResult<object>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepository<Supplier> supplierRepository;

        public SupplierUpdateCommandHandler(IMapper mapper, IBaseRepository<Supplier> supplierRepository)
        {
            this.mapper = mapper;
            this.supplierRepository = supplierRepository;
        }

        public async Task<APIResult<object>> Handle(SupplierUpdateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();

            var info = mapper.Map<Supplier>(request);

            var entity = supplierRepository.GetAll().Result.FirstOrDefault(x => x.SupplierId == request.SupplierId);
            entity.SupplierId = request.SupplierId;
            entity.SupplierCode = request.SupplierCode;
            entity.SupplierName = request.SupplierName;
            entity.SupplierType = request.SupplierType;
            entity.SupplierAddress = request.SupplierAddress;
            entity.SupplierPhone = request.SupplierPhone;
            entity.City = request.City;
            entity.Status = request.Status;
            entity.Country = request.Country;
            entity.SupplierCategory = request.SupplierCategory;
            entity.SupplierTag = request.SupplierTag;
            entity.CompanyFlag = request.CompanyFlag;
            entity.OutsourcingFlag = request.OutsourcingFlag;
            var upinfo = supplierRepository.UpdateAsync(entity).Result;

            if (upinfo > 0)
            {
                result.Code = APIEnums.修改成功;
                result.Msg = APIEnums.修改成功.ToString();
                result.data = upinfo;
            }
            else
            {
                result.Code = APIEnums.修改失败;
                result.Msg = APIEnums.修改失败.ToString();
            }

            return await Task.FromResult(result);
        }
    }
}
